from django.forms import model_to_dict

from goodsApp.goodsModel.models import Goods
from goodsApp.service.goodService import GoodsService
from orderApp.cartModel.models import CartTable



class CartService:

    def __init__(self):
        self.goodsService = GoodsService()

    def addGoods(self,userId, goodsId, amount):
        if self.goodsService.isExist(goodsId):
            print("添加商品")
            goods =self.goodsService.getGoods(goodsId)
            price = float(goods.price)
            print(price)
            print(price*int(amount))
            shoppingCart = CartTable(user_id=userId, goods_id=goodsId, amount=amount,total_price=price*int(amount))
            shoppingCart.save()

    def removeGoods(self,userId,cid):
        CartTable.objects.get(user_id=userId,id=cid).delete()

    def clearGoods(self,userId):
        CartTable.objects.filter(user_id=userId).delete()

    def update(self,userId,goods):
        CartTable.objects.filter(user_id=userId,goods_id=goods['goodsId']).update(
            amount = goods['amount']
        )
    def getByUserId(self,userId):
         result = []
         index = 0
         for gs in CartTable.objects.filter(user_id=userId):
             result.append(model_to_dict(gs))
             result[index]['info'] = Goods.objects.values('img','price','title').get(id=gs.goods_id)
             index+=1
         return result



